package org.budo.graph.service.util;

import java.util.Collection;

import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.budo.support.lang.util.ReflectUtil;
import org.budo.support.spring.util.SpringUtil;
import org.springframework.context.ApplicationContext;

/**
 * @author limingwei
 */
public class MybatisMapperUtil {
    private static final boolean HAS_MYBATIS = ReflectUtil.hasClass("org.apache.ibatis.session.SqlSessionFactory");

    public static String writeMybatisMapperResponse(ApplicationContext applicationContext, String url) {
        if (!HAS_MYBATIS) {
            return "NOT_HAS_MYBATIS";
        }

        SqlSessionFactory sessionFactory = SpringUtil.getBean(applicationContext, SqlSessionFactory.class);
        if (null == sessionFactory) {
            return "SQL_SESSION_FACTORY_IS_NULL";
        }

        Configuration configuration = sessionFactory.getConfiguration();
        Collection<MappedStatement> mappedStatements = configuration.getMappedStatements();

        if (null == mappedStatements || mappedStatements.isEmpty()) {
            return "NO_MAPPED_STATEMENT";
        }

        String response = "<pre>";
        int i = 1;
        for (Object each : mappedStatements) {
            if (null == each || !(each instanceof MappedStatement)) {
                response += "" + (i++) + ". " + each + "\n";
                continue;
            }

            MappedStatement mappedStatement = (MappedStatement) each;
            SqlSource sqlSource = mappedStatement.getSqlSource();
            Integer timeout = mappedStatement.getTimeout();

            response += "" + (i++) + ". " + mappedStatement.getId() + ", "; //
            response += "sqlSource=" + sqlSource;

            if (null != timeout) {
                response += ", {timeout=" + timeout + "}";
            }

            response += "\n";
        }
        return response + "</pre>";
    }
}
